package com.hejie.service.notification.repository;

import com.hejie.service.notification.entity.Notification;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface NotificationRepository extends JpaRepository<Notification, Long> {

    // 根据用户ID查询通知（分页）
    Page<Notification> findByUserIdAndIsDeletedFalseOrderByCreatedAtDesc(
            @Param("userId") Long userId,
            Pageable pageable);

    // 统计未读通知数量
    long countByUserIdAndIsReadFalseAndIsDeletedFalse(
            @Param("userId") Long userId);

    // 标记单个通知为已读
    @Modifying
    @Query("UPDATE Notification n SET n.isRead = true WHERE n.id = :notificationId AND n.userId = :userId")
    int markAsReadById(@Param("notificationId") Long notificationId, @Param("userId") Long userId);

    // 标记所有通知为已读
    @Modifying
    @Query("UPDATE Notification n SET n.isRead = true WHERE n.userId = :userId AND n.isRead = false AND n.isDeleted = false")
    int markAllAsRead(@Param("userId") Long userId);

    // 批量删除通知（逻辑删除）
    @Modifying
    @Query("UPDATE Notification n SET n.isDeleted = true WHERE n.id IN :notificationIds AND n.userId = :userId")
    int deleteByIds(@Param("notificationIds") Iterable<Long> notificationIds, @Param("userId") Long userId);

    // 删除用户所有通知（逻辑删除）
    @Modifying
    @Query("UPDATE Notification n SET n.isDeleted = true WHERE n.userId = :userId")
    int deleteAllByUserId(@Param("userId") Long userId);
}